import React from 'react';
import ReactDOM from 'react-dom';
import {Provider,connect} from 'react-redux';
import {createStore,combineReducers} from 'redux';
import prefixNamespace from './prefixNamespace'

export {connect}

function dva(){
  const app = {
    _models:[],
    _router:null,
    model,
    router,
    start
  }

  const initialReducers = {};

  function model(model/*model options*/){
    const prefixedModel = prefixNamespace(model);
    app._models.push(model);
    return prefixedModel;
  }

  function router(router){
    app._router = router;
  }

  function start(root){
    for (const model of app._models) {
      initialReducers[model.namespace] = getReducer(model);
    }

    const rootReducer = createReducer();

    const store = createStore(rootReducer);

    ReactDOM.render(
      <Provider store={store}>
        {app._router()}
      </Provider>,
      document.querySelector(root)
    );

    function createReducer(){
      return combineReducers(initialReducers);
    }
  }

  /**
      {
        namespace: 'counter1',
        state: {number: 0},
        reducers: {
          //处理器对象的key再加上上面写的命名空间(namespace), 就是组件里你对应需要派发的动作名 (props.dispatch({type: 'counter/add'})
          add(state) {
            return {number: state.number + 1}
          }
        }
      }

      === ↑转变成↓ ===
      符合 redux 规范的 reducer
   */
  function getReducer(model){
    const {state: initialState, reducers} = model;
    const reducer = (state = initialState, action) => {
      const reducer = reducers[action.type]; //action.type = counter1/add
      if(reducer) return reducer(state);
      return state;
    };
    return reducer;
  }

  return app;
}

export default dva;
